package vip.xiaonuo.modular.gaode;


import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.*;

/**
 * @Description 通过经纬度计算所属行政区域
 * @Author cy
 * @Date 2022/8/4 12:46
 * @Version 1.0
 */
@Slf4j
public class CoordinateConvertAddr {
    private static final String HOSTARR = "http://restapi.amap.com/v3/geocode/regeo";
    private static final String LOCATION_URL = "https://restapi.amap.com/v3/geocode/geo?parameters";
    private static final String HOST = "https://restapi.amap.com/v3/distance";
//  7c43b1c03de48c165e24a0ea966b99ba
//  3a123453eb2bbbf4acb2f9593e557c6b
//  560307d64f609d01bd9be6d69c1a173a
//  98227a7b28b0811f8fc98e2e4b154589 企业级key
    private static final String KEY = "98227a7b28b0811f8fc98e2e4b154589";

    private static final int MAX_LOCATION_NUM = 20;
    /**
     * 单组经纬度-逆地理编码
     * @author: cy
     * @Date: 2022/8/4 13:49
     * @param location: 经纬度格式：115.40331688781271,31.67743685664941
     * @return: java.lang.String[]
     **/
    public static String[] getLocationAddr(String location){
        List<NameValuePair> list = new LinkedList<NameValuePair>();
        list.add(new BasicNameValuePair("key", KEY));
        list.add(new BasicNameValuePair("output", "JSON"));
        list.add(new BasicNameValuePair("location", location));

        String responseEntity = null;
        String addr="";
        try {
            HttpGet httpGet = new HttpGet(new URIBuilder(HOSTARR).setParameters(list).build());
            httpGet.setConfig(RequestConfig.custom().setConnectTimeout(2000).build());
            HttpResponse response = HttpClients.createDefault().execute(httpGet);
            responseEntity = EntityUtils.toString(response.getEntity(), "UTF-8");
            JSONObject jsonObject = JSON.parseObject(responseEntity);
            System.out.println(jsonObject);
            addr=jsonObject.getJSONObject("regeocode").getString("formatted_address");
            String addr0 = addr.substring(0,addr.indexOf("省")+1);
            int num = addr.indexOf('市');
            String addr1 = addr.substring(addr.indexOf("省") + 1,num+1);
            if(addr.contains("区")) {
                addr = addr.substring(addr.indexOf("省") + 1, addr.indexOf("区") + 1);
                addr1 = addr1 + "," + addr.substring(addr.indexOf('市')+1,addr.indexOf("区") + 1);
            }
            else if(addr.contains("县")){
                addr = addr.substring(addr.indexOf("省") + 1, addr.indexOf("县") + 1);
                addr1 = addr1 + "," + addr.substring(addr.indexOf('市')+1,addr.indexOf("县") + 1);
            }else{
                addr = addr.substring(addr.indexOf("省") + 1,  addr.lastIndexOf("市") + 1);
                addr1 = addr1 + "," + addr.substring(addr.indexOf('市')+1,addr.lastIndexOf("市") + 1);
            }
            location = location + "," + addr0+","+addr1;

        } catch (Exception e) {
            if (e instanceof ConnectTimeoutException) {
                System.out.println("-------请求超时-------");
            } else {
                e.printStackTrace();
            }
        }
        String[] log_latitude = location.split(",");
        return log_latitude;
    }

    /**
     * 批量经纬度-逆地理编码
     * @author: cy
     * @Date: 2022/8/4 13:49
     * @param location: 经纬度格式：115.40331688781271,31.67743685664941;115.40331688781271,31.67743685664941
     * @return: java.lang.String[]
     **/
    public static String[] getBatchLocationAddr(String location){
        List<NameValuePair> list = new LinkedList<NameValuePair>();
        list.add(new BasicNameValuePair("key", KEY));
        list.add(new BasicNameValuePair("output", "JSON"));
        list.add(new BasicNameValuePair("location", location));
        list.add(new BasicNameValuePair("batch", "true"));

        String responseEntity = null;
        try {
            HttpGet httpGet = new HttpGet(new URIBuilder(HOSTARR).setParameters(list).build());
            httpGet.setConfig(RequestConfig.custom().setConnectTimeout(2000).build());
            HttpResponse response = HttpClients.createDefault().execute(httpGet);
            responseEntity = EntityUtils.toString(response.getEntity(), "UTF-8");
            JSONObject jsonObject = JSON.parseObject(responseEntity);
            JSONArray regeocodes = jsonObject.getJSONArray("regeocodes");
            for (int i = 0; i < regeocodes.size(); i++) {
                JSONObject regeocodesJSONObject = regeocodes.getJSONObject(i);
                JSONObject addressComponent = regeocodesJSONObject.getJSONObject("addressComponent");
                String province = addressComponent.getString("province");
                String city = addressComponent.getString("city");
                String district = addressComponent.getString("district");
                location = location + "," + province+","+city+","+district;
            }
        } catch (Exception e) {
            if (e instanceof ConnectTimeoutException) {
                System.out.println("-------请求超时-------");
            } else {
                e.printStackTrace();
            }
        }
        String[] log_latitude = location.split(",");
        return log_latitude;
    }

    /**
     * 批量经纬度-逆地理编码
     * @author: cy
     * @Date: 2022/8/4 13:49
     * @param address: 经纬度格式：115.40331688781271,31.67743685664941;115.40331688781271,31.67743685664941
     * @return: java.lang.String[]
     **/
    public static LngLat getBatchLngLatAddr(String address){
        List<NameValuePair> list = new LinkedList<NameValuePair>();
        list.add(new BasicNameValuePair("key", KEY));
        list.add(new BasicNameValuePair("output", "JSON"));
        list.add(new BasicNameValuePair("address", address));
        String responseEntity = null;
        LngLat lngLat=new LngLat();
        try {
            HttpGet httpGet = new HttpGet(new URIBuilder(LOCATION_URL).setParameters(list).build());
            httpGet.setConfig(RequestConfig.custom().setConnectTimeout(2000).build());
            HttpResponse response = HttpClients.createDefault().execute(httpGet);
            responseEntity = EntityUtils.toString(response.getEntity(), "UTF-8");
            JSONObject jsonObject = JSON.parseObject(responseEntity);
            JSONArray geocodes = jsonObject.getJSONArray("geocodes");
            for (int i = 0; i < geocodes.size(); i++) {
                JSONObject geocodesJSONObject = geocodes.getJSONObject(i);
                lngLat.setLongitude(geocodesJSONObject.getString("location").split(",")[0]);
                lngLat.setLatitude(geocodesJSONObject.getString("location").split(",")[1]);
                lngLat.setProvName(geocodesJSONObject.getString("province"));
                lngLat.setCityName(geocodesJSONObject.getString("city"));
                lngLat.setCoutryName(geocodesJSONObject.getString("district"));
            }
        } catch (Exception e) {
            if (e instanceof ConnectTimeoutException) {
                System.out.println("-------请求超时-------");
            } else {
                e.printStackTrace();
            }
        }
        return lngLat;
    }
    //114.818312 30.831722, 114.818312 30.834172, 114.82079200000001 30.834172, 114.82079200000001 30.831722, 114.818312 30.831722
    public static void main(String[] args) throws InterruptedException {
        List<String> list = new ArrayList<>();
        list.add("108.274865,23.158533");
        list.add("115.068375,30.296504");
        list.add("118.792281,34.093004");
        Map<String, Address> batchLocationAddrMap = getBatchLocationAddrMap(list);
        for (String s : batchLocationAddrMap.keySet()) {
//            System.out.println(s + " :" +batchLocationAddrMap.get(s));

        }

        String[] batchLocationAddr = getBatchLocationAddr("108.274865,23.158533");
        for (String s : batchLocationAddr) {
            System.out.println(s);
        }

    }

    public static Map<String,Address> getBatchLocationAddrMap(List<String> locationList){
        List<List<String>> locations = ListUtil.split(locationList, MAX_LOCATION_NUM);
        Map<String,Address> addressMap = new HashMap<>();
        log.info(">>>本次调用 {} 次高德逆编码服务接口！", locations.size());
        for (List<String> stringList : locations) {
            String location = StringUtils.join(stringList, "|");
            List<NameValuePair> list = new LinkedList<NameValuePair>();
            list.add(new BasicNameValuePair("key", KEY));
            list.add(new BasicNameValuePair("output", "JSON"));
            list.add(new BasicNameValuePair("location", location));
            list.add(new BasicNameValuePair("batch", "true"));
            String responseEntity = null;
            try {
                HttpGet httpGet = new HttpGet(new URIBuilder(HOSTARR).setParameters(list).build());
                httpGet.setConfig(RequestConfig.custom().setConnectTimeout(2000).build());
                HttpResponse response = HttpClients.createDefault().execute(httpGet);
                responseEntity = EntityUtils.toString(response.getEntity(), "UTF-8");
                JSONObject jsonObject = JSON.parseObject(responseEntity);
                JSONArray regeocodes = jsonObject.getJSONArray("regeocodes");
                if (ObjectUtil.isEmpty(regeocodes)) {
                    continue;
                }
                for (int i = 0; i < regeocodes.size(); i++) {
                    JSONObject regeocodesJSONObject = regeocodes.getJSONObject(i);
                    JSONObject addressComponent = regeocodesJSONObject.getJSONObject("addressComponent");
                    Address address = new Address();
                    address.setProvName(addressComponent.getString("province"));
                    address.setCityName(addressComponent.getString("city"));
                    address.setCountryName(addressComponent.getString("district"));
                    addressMap.put(stringList.get(i), address);
                }
            } catch (Exception e) {
                if (e instanceof ConnectTimeoutException) {
                    log.error("高德逆地理编码接口请求超时");
                } else {
                    log.error("解析坐标错误！", e);
                }
            }
        }
        return addressMap;
    }
}
